package com.howard.dao;

import java.lang.reflect.InvocationTargetException;

import javax.sql.DataSource;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.howard.core.AbstractBasicCoreDao;

/**
 * 抽象基类Dao
 *
 * @author <a href="mailto:howard.he0329@gmail.com">Howard.He</a>
 *
 */
public abstract class AbstractCoreDao<T> {

	/** log */
	protected static Logger logger = LoggerFactory
			.getLogger(AbstractBasicCoreDao.class);

	@Autowired
	private DataSource routingDataSource;

	private JdbcTemplate jdbcTemplate;

	private SimpleJdbcTemplate simpleJdbcTemplate;

	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Autowired
	public void init() {
		jdbcTemplate = new JdbcTemplate(routingDataSource);
		simpleJdbcTemplate = new SimpleJdbcTemplate(routingDataSource);
		namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
				routingDataSource);
		jdbcTemplate.setFetchSize(1000);
		if (logger.isInfoEnabled()) {
			logger.info("jdbcTemplate: " + jdbcTemplate);
		}
	}

	public void setRoutingDataSource(final DataSource routingDataSource) {
		this.routingDataSource = routingDataSource;
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public SimpleJdbcTemplate getSimpleJdbcTemplate() {
		return simpleJdbcTemplate;
	}

	public void setSimpleJdbcTemplate(
			final SimpleJdbcTemplate simpleJdbcTemplate) {
		this.simpleJdbcTemplate = simpleJdbcTemplate;
	}

	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return namedParameterJdbcTemplate;
	}

	public void setNamedParameterJdbcTemplate(
			final NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
	}

	@SuppressWarnings("unchecked")
	public long insert(SimpleJdbcInsert insert, T entity)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, DataAccessException {
		return insert.executeAndReturnKey(PropertyUtils.describe(entity))
				.longValue();
	}

}
